 //
//  VideoDetailViewController.m
//  Hxcsfw
//
//  Created by qiysoft on 2017/10/30.
//  Copyright © 2017年 企友软mac. All rights reserved.
//
/*
 //WSCREENH_HEIGHT - (WSCREENH_HEIGHT - WSCREENH_WIDTH*9/16)上面的高度
 //(WSCREENH_HEIGHT - WSCREENH_WIDTH*9/16) 下面的高度
 //“课程简介”和“答疑讨论”弹出框的Frame
 [self setFrame:CGRectMake(0, WSCREENH_HEIGHT - (WSCREENH_HEIGHT - WSCREENH_WIDTH*9/16), ScreenWidth, (WSCREENH_HEIGHT - WSCREENH_WIDTH*9/16))];
 */

#import "VideoDetailViewController.h"
#import "VideoDetailCellA.h"
#import "VideoDetailCellB.h"
#import "CJPresentView.h"
#import "UIView+CCJExtension.h"
#define VideoDetailCellAIndentifier @"VideoDetailCellAIndentifier"
#define VideoDetailCellBIndentifier @"VideoDetailCellBIndentifier"
#import "CLPlayerView.h"
#import "UIView+CLSetRect.h"
#import "VideoDetailModel.h"
#import "HHNonePage.h"
#import "IQKeyboardManager.h"
#import "BuyVIPViewController.h"
#import "LoginViewController.h"
#import <UShareUI/UShareUI.h>
#import "UIImageView+WebCache.h"
#import "NSObject+ZM.h"
#import "Masonry.h"
#import "AccountViewController.h"

@import StoreKit;

@interface VideoDetailViewController ()<UITableViewDelegate,UITableViewDataSource,MoreCellDelegate,UITextViewDelegate,UIWebViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate>
{
    VideoDetailCellA *cell1;
    VideoDetailCellB *cell2;
    UITextView *_textView;
    UIButton *fsBtn;
    VideoDetailModel *videoModel;
    CGFloat webHight;
    CGFloat titH;
    int j;
    UIView *viewContent;
    UIView *bgMebemView;

    UIView *memberVcontent;
    UIView *bgSleMemberV;
    NSDictionary *jFDic;

    NSString *strKxkcs;
}

@property (strong, nonatomic) IBOutlet UIView *bgView;

@property (nonatomic,weak) CLPlayerView *playerView;
@property (strong, nonatomic) CJPresentView *PresentView;
@property (strong, nonatomic) CJPresentView *PresentView2;
@property (nonatomic,strong) NSMutableArray *XQArray;
@property (nonatomic,strong) NSMutableArray *PLArray;
@property (nonatomic,strong) NSMutableArray *QBPLArray;

@property (nonatomic, strong) UIView *inputView;
@property (nonatomic, strong) UIButton *btnSend;
@property (strong, nonatomic) UILabel *lbWBZContent; // 限制输入500字内容
@property (nonatomic, strong) UILabel *lbOfPlaceholder;
@property (strong, nonatomic) UIWebView *webView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic ,strong) NSString *shareUrl;// 分享的URL

@end

@implementation VideoDetailViewController

- (CJPresentView *)PresentView
{
    if (!_PresentView)
    {
        _PresentView = [CJPresentView viewFromXib];
    }
    return _PresentView;
}

- (CJPresentView *)PresentView2
{
    if (!_PresentView2)
    {
        _PresentView2 = [CJPresentView viewFromXib];
    }
    return _PresentView2;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSArray *array = [touches allObjects];
    CGFloat height = [[array lastObject] locationInView:self.view].y;
    
    if (self.PresentView.viewY == WSCREENH_HEIGHT || height >= WSCREENH_HEIGHT * 0.3)
    {
        
    }
    else
    {
        [self.PresentView completeCLick:nil];
    }
    if (self.PresentView2.viewY == WSCREENH_HEIGHT || height >= WSCREENH_HEIGHT * 0.3)
    {
        
    }
    else
    {
        [self.PresentView2 completeCLick:nil];
    }
    UIView *bgView = [self.view viewWithTag:20000];
    [bgView removeFromSuperview];
    [_textView resignFirstResponder];

}

- (UITableView *)tableView {
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50, WSCREENH_WIDTH, (WSCREENH_HEIGHT - WSCREENH_WIDTH*9/16)-50) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UIWebView *)webView {
    if (_webView == nil) {
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 50, WSCREENH_WIDTH, WSCREENH_HEIGHT)];
        NSString *content;
        WLog(@"%@",[self.XQArray[0] brief]);
        if ([self.XQArray[0] brief].length > 0) {
            
            content = [self.XQArray[0] brief];
            [_webView loadHTMLString:content baseURL:nil];
        }else {
            
            content = @"---";
            [_webView loadHTMLString:content baseURL:nil];
        }
//        [_webView setScalesPageToFit:YES];
        _webView.delegate = self;
        _webView.scrollView.bounces = NO;
    }
    return _webView;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{

    // --- 注入js代码自适应富文本内容宽度
    NSString *js = @"function imgAutoFit(){\
    var imgs = document.getElementsByTagName('img');\
    for (var i = 0; i < imgs.length; ++i) {\
    var img = imgs[i];\
    img.style.maxWidth = %f;\
    }\
    }";
    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];
    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
    // --- 注入js代码自适应富文本内容宽度
    
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];

    webHight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];

    webView.frame = CGRectMake(0, 50, WSCREENH_WIDTH, (WSCREENH_HEIGHT - WSCREENH_WIDTH*9/16) - 50);

//    [self.tableView reloadData];
}

-(void)MoreAA:(UIButton *)button{
    
    if (self.PresentView.viewY == WSCREENH_HEIGHT)
    {
        self.PresentView.x = 0;
        // 设置这个Xib 一开始在屏幕的底部(这样能和键盘的动画保持同步)
        self.PresentView.y = WSCREENH_HEIGHT;
        self.PresentView.width = WSCREENH_WIDTH;
        self.PresentView.height = WSCREENH_HEIGHT * 0.5;
        self.PresentView.Title.text = @"课程简介";
        [self.view addSubview:self.PresentView];
        
        [self.PresentView animeData];
        //[self.XQArray[indexPath.row] brief] 课程简介
        [self.PresentView addSubview:self.webView];
    }
}

-(void)MoreBB:(UIButton *)button{
//    [self.tableView.header beginRefreshing];
    [self PingLunDataRequest];//下载详情全部评论列表
    if (self.PresentView2.viewY == WSCREENH_HEIGHT)
    {
        self.PresentView2.x = 0;
        // 设置这个Xib 一开始在屏幕的底部(这样能和键盘的动画保持同步)
        self.PresentView2.y = WSCREENH_HEIGHT;
        self.PresentView2.width = WSCREENH_WIDTH;
        self.PresentView2.height = WSCREENH_HEIGHT * 0.5;
        self.PresentView2.Title.text = @"答疑讨论";
        [self.view addSubview:self.PresentView2];
        
        [self.PresentView2 animeData];

        [self.PresentView2 addSubview:self.tableView];
        
        [self.tableView.superview insertSubview:[UIView new] atIndex:0];

        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES; //影藏nav
    [self VideoDetailDataRequest];//返回有问题：返回的(json字符串格式的)解密数据EC1002
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO; //影藏nav
}

- (void)viewDidLoad {
    [super viewDidLoad];

//    [WShareUtil sharedData].dicBuySymbol = @{@"boughten":@"1",@"chosen":@"0",@"id":_strId,@"symbol":_symbol};
    self.textViewQ.layer.masksToBounds = YES;
    self.textViewQ.layer.cornerRadius = 18;
//    self.textView.layer.borderWidth = 0.5;
//    self.textView.layer.borderColor = [[UIColor grayColor] CGColor];
    // 1.注册控件
    UINib *cellNib = [UINib nibWithNibName:@"VideoDetailCellA" bundle:nil];
    [self.myTableView registerNib:cellNib forCellReuseIdentifier:VideoDetailCellAIndentifier];
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.prototypeCell  = [self.myTableView dequeueReusableCellWithIdentifier:VideoDetailCellAIndentifier];
    
    // 2.注册控件
    UINib *cellNib2 = [UINib nibWithNibName:@"VideoDetailCellB" bundle:nil];
    [self.myTableView registerNib:cellNib2 forCellReuseIdentifier:VideoDetailCellBIndentifier];
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.prototypeCell  = [self.myTableView dequeueReusableCellWithIdentifier:VideoDetailCellBIndentifier];
    
    self.PresentView.viewY = WSCREENH_HEIGHT;
    self.PresentView2.viewY = WSCREENH_HEIGHT;

    _XQArray = [NSMutableArray array];
    _PLArray = [NSMutableArray array];//列表评论
    _QBPLArray = [NSMutableArray array];//全部评论
    _shareUrl = [NSString string];
    WLog(@"%@",_strId);
    
//    [self PingLunDataRequest];//下载详情全部评论列表
    [self requestPingLunListDataisRefresh:YES];//下载详情评论列表

    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    _inputView = [[UIView alloc]initWithFrame:CGRectMake(0, WSCREENH_HEIGHT, WSCREENH_WIDTH, 60)];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wkeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wkeyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KCGMNOTIFI) name:@"KCGM" object:nil];
}

- (void)KCGMNOTIFI {
    WLog(@"课程购买");
    BuyVIPViewController *bugVc = [[BuyVIPViewController alloc] init];
    bugVc.title = @"订单明细";
    bugVc.vdModel = self.XQArray[0];
    [self.navigationController pushViewController:bugVc animated:YES];
}

#pragma mark - 下载视频详情页面的内容
- (void)VideoDetailDataRequest {

    [WShareUtil sharedData].isShowWait = YES;

    //mode:native,service:train,content:{revert:detail,id:?}

    NSString *username;
    NSString *nologinuser = [WShareUtil getUUID];

    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"revert":@"detail",@"id":_strId,@"apptype":@"ios"}};
    }else {

         parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"revert":@"detail",@"id":_strId,@"apptype":@"ios",@"nologinuser":nologinuser}};
    }

    WLog(@"请求视频详情参数：%@",parametersDict);
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    //    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};
    
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([returnDic[@"resultCode"] isEqualToString:@"WRONG_ARTICAL"]) {
            [self.navigationController popViewControllerAnimated:YES];

            [SVProgressHUD showImage:nil status:@"此课程已经过期"];
            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
            [SVProgressHUD dismissWithDelay:1.];
            [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];
        }
        
        [self.XQArray removeAllObjects];
        
        VideoDetailModel *vdModel = [VideoDetailModel mj_objectWithKeyValues:returnDic];

        [self.XQArray addObject:vdModel];

        if ([vdModel.isfree isEqualToString:@"Y"] || [vdModel.payments isEqualToString:@"paid"] ||[vdModel.payments isEqualToString:@"gjhy"]) {//免费或交了钱的
            [self canWatchCourse];
        }
//        else if ([vdModel.isfree isEqualToString:@"N"] & [vdModel.payments isEqualToString:@"cphylim"] ||[vdModel.payments isEqualToString:@"nologin"] ||[vdModel.payments isEqualToString:@"paiderror"] || [vdModel.payments isEqualToString:@"nopay"]){
//        }

        [_myTableView reloadData];
        
    } failure:^(NSError *error) {
        [WShareUtil showAlert:ALERT_TITLE message:@"请求超时"];
        WLog(@"失败");
    } showProgress:YES];
}

- (void)canWatchCourse {
    _bgView.hidden = YES;
    [self MFSTBtn:nil];
}

#pragma mark - 下载视频详情页面全部的评论
- (void)PingLunDataRequest {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noWifiRefershingEnd) name:REFRESHINGEND object:nil];
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self requestListDataStrNum:@"1" isRefresh:YES];
        j = 1;
    }];
    
    //    if (kIsHaveNetwork) //有网
    //    {
    //        [_myTableView.header beginRefreshing];
    //    } //else无网
    [self.tableView.header beginRefreshing];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        NSString *num = [NSString stringWithFormat:@"%d",++j];
        [self requestListDataStrNum:num isRefresh:NO];
    }];

}
- (void)noWifiRefershingEnd {
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
    [WShareUtil sharedData].isShowWait = YES;
}

#pragma mark - 下载视频详情页面评论
- (void)requestPingLunListDataisRefresh:(BOOL)isRefresh{

    NSDictionary *parametersDict;
    NSString *nologinuser = [WShareUtil getUUID];

    if ([WShareUtil strNilOrEmpty:_strId]) {
        _strId = @"";
    }
    if ([WShareUtil sharedData].dicSession) {
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"revert":@"paginate",@"from":@"xt",@"id":_strId,@"pagesize":@"5",@"pagenumber":@"1",@"apptype":@"ios"}};
    } else {
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"nologinuser":nologinuser,@"revert":@"paginate",@"from":@"xt",@"id":_strId,@"pagesize":@"5",@"pagenumber":@"1",@"apptype":@"ios"}};
    }
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    //    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};
    
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if (isRefresh) {
            [self.PLArray removeAllObjects];
        }
        for (NSDictionary *dic in returnDic[@"data"]) {
            VideoDetailModel *vdModel = [VideoDetailModel mj_objectWithKeyValues:dic];
            [self.PLArray addObject:vdModel];
        }
        
        [_myTableView reloadData];
        [_tableView reloadData];
        
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        
        if ([returnDic[@"data"] count] < 10) {
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.tableView.footer endRefreshingWithNoMoreData];
        }
        
    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (void)requestListDataStrNum:(NSString *)pageNum isRefresh:(BOOL)isRefresh{
    //mode:native,service:comment,content:{revert:paginate,from:xt,id:课程id,pagesize:?,pagenumber:?}

    NSString *username;
    NSString *nologinuser = [WShareUtil getUUID];

    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"revert":@"paginate",@"from":@"xt",@"id":_strId,@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};
    }else {
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"nologinuser":nologinuser,@"revert":@"paginate",@"from":@"xt",@"id":_strId,@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};
    }
   
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    //    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};
    
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if (isRefresh) {
            [self.QBPLArray removeAllObjects];
        }
        for (NSDictionary *dic in returnDic[@"data"]) {
            VideoDetailModel *vdModel = [VideoDetailModel mj_objectWithKeyValues:dic];
            [self.QBPLArray addObject:vdModel];
        }
        
        [_tableView reloadData];

        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        
        ///* --- 图片式提醒
        UIView *view = [self.myTableView viewWithTag:10000];
        [view removeFromSuperview];
        HHNonePage *_nonePage = [[HHNonePage alloc]init];
        _nonePage = nil;
        if (_PLArray.count == 0) {
            _nonePage = [[HHNonePage alloc] initWithFrame:CGRectMake(0, -120, self.view.frame.size.width, self.view.frame.size.height)];
            _nonePage.tag = 10000;
            [self.tableView addSubview:_nonePage];
        }
        //*/
        
        if ([returnDic[@"data"] count] < 10) {
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.tableView.footer endRefreshingWithNoMoreData];
        }
        
    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//设置UITableViewCell的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        cell2  = [[[NSBundle mainBundle] loadNibNamed:@"VideoDetailCellB" owner:self options:nil] lastObject];
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (self.QBPLArray.count > 0 && self.QBPLArray != nil) {
            //cell2.plrLB.text = [self.QBPLArray[indexPath.row] plr];//评论人
            cell2.plrLB.text = @"网友";//评论人
            cell2.fbsjLB.text = [self.QBPLArray[indexPath.row] fbsj];//发布时间
            cell2.contentLB.text = [self.QBPLArray[indexPath.row] content];//评论内容
            
            if ([self.QBPLArray[indexPath.row] reply] != nil || [self.QBPLArray[indexPath.row] reply] != NULL) {
                
                //cell2.replyplrLB.text = [NSString stringWithFormat:@"%@回复",[[self.QBPLArray[indexPath.row] reply][0] valueForKey:@"plr"]];//回复人
                cell2.replyContentLB.text = [[self.QBPLArray[indexPath.row] reply][0] valueForKey:@"content"];//回复内容
            }else{
                cell2.HFView.hidden = YES;
            }
        }
        
        return cell2;
    }else{
        if (indexPath.section == 0) {
            cell1  = [[[NSBundle mainBundle] loadNibNamed:@"VideoDetailCellA" owner:self options:nil] lastObject];
            cell1.selectionStyle = UITableViewCellSelectionStyleNone;
            cell1.delegate = self;
            
            if (self.XQArray.count > 0 && self.XQArray != nil) {
                
                //是否显示免费试听按钮
                if ([WShareUtil strNilOrEmpty:[self.XQArray[indexPath.row] freeurl]]) {
                    self.MFSTbtn.hidden = YES;
                    self.LJGMyou.constant = -50;
                }
                
                //背景大图片
                if (![WShareUtil strNilOrEmpty:[self.XQArray[indexPath.row] imgsrc]]) {
                    [self.BgImg sd_setImageWithURL:[NSURL URLWithString:[self.XQArray[indexPath.row] imgsrc]] placeholderImage:[UIImage imageNamed:@"KCMX_1.png"]];
                }

                //视频下标题
                cell1.titleLB.text = [self.XQArray[indexPath.row] StrTitlestr];
                
                //标题添加单例，在视频上方显示
                [WShareUtil sharedData].VideoTitle = cell1.titleLB.text;

                cell1.viewLB.text = [NSString stringWithFormat:@"%@人学习过",[self.XQArray[indexPath.row] StrView]];
                //[vdModel.isfree isEqualToString:@"Y"]  [self.XQArray[indexPath.row] charged]
                if ([[self.XQArray[indexPath.row] isfree] isEqualToString:@"Y"]) {
                    cell1.chargedLB.text = @"免费";//费用
                    cell1.chargedLB.textColor = [UIColor colorWithRed:0.37 green:0.71 blue:0.11 alpha:1];
                    
                }else{
                    cell1.chargedLB.text = [NSString stringWithFormat:@"¥ %@",[self.XQArray[indexPath.row] charged]];//费用
                    //收费的话不能分享
                    self.FenXiangBtn.hidden = YES;
                    self.TextViewrightDistance.constant = 47;
                    self.TextBtnrightDistance.constant = 47;
                }
                
                //概要内容去掉标签，正常显示
                cell1.briefLB.text = [WShareUtil filterHTML:[self.XQArray[indexPath.row] brief]];
                cell1.briefLB.text = [cell1.briefLB.text stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];//去掉特殊符号
                cell1.briefLB.text = [cell1.briefLB.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//去掉左右两端的空格
                
                // 三方库设置行间距。字间距
                cell1.briefLB.attributedText = [[cell1.briefLB.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] getAttributedWithString:[cell1.briefLB.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] WithLineSpace:2 kern:0 font:[UIFont systemFontOfSize:13.0]];
                
//                CGSize lblSize = [[cell1.briefLB.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] getAttributionHeightWithString:[cell1.briefLB.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] lineSpace:1.2 kern:2 font:[UIFont systemFontOfSize:13.0] width:300];
                
//                cell1.briefLB.text = [self.XQArray[indexPath.row] brief];//概要
                
            }
            
            return cell1;
        }else{
            cell2  = [[[NSBundle mainBundle] loadNibNamed:@"VideoDetailCellB" owner:self options:nil] lastObject];
            cell2.selectionStyle = UITableViewCellSelectionStyleNone;
            
            if (self.PLArray.count > 0 && self.PLArray != nil) {
                //cell2.plrLB.text = [self.PLArray[indexPath.row] plr];//评论人
                cell2.plrLB.text = @"网友";//评论人
                cell2.fbsjLB.text = [self.PLArray[indexPath.row] fbsj];//发布时间
                cell2.contentLB.text = [self.PLArray[indexPath.row] content];//评论内容
                
                if ([self.PLArray[indexPath.row] reply] != nil || [self.PLArray[indexPath.row] reply] != NULL) {
                    
                    //cell2.replyplrLB.text = [NSString stringWithFormat:@"%@回复",[[self.PLArray[indexPath.row] reply][0] valueForKey:@"plr"]];//回复人
                    cell2.replyContentLB.text = [[self.PLArray[indexPath.row] reply][0] valueForKey:@"content"];//回复内容
                }else{
                    cell2.HFView.hidden = YES;
                }
            }
            return cell2;
        }
    }
}

//行点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
}

//分组个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.tableView) {
        return 1;
    }else{
        return 2;

    }
}

//列表行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (tableView == self.tableView) {
        return self.QBPLArray.count;
    }else{
        if (section == 0) {
            return 1;
        }else{
            return self.PLArray.count;
        }
    }
}

//设置行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    
    if (tableView == self.tableView) {
//        self.tableView.frame = CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT - WSCREENH_HEIGHT * (190.0/375) - 50 - 64);
//        return webHight + 41 + titH;
        if ([self.QBPLArray[indexPath.row] reply] != nil || [self.QBPLArray[indexPath.row] reply] != NULL) {
            return 152;
        }else{
            return 152 - 80;
        }
    }else{
        if (indexPath.section == 0) {
            if (self.PLArray.count == 0) {
                return 400;
            }else{
                return 230;
            }
        }else{
            if ([self.PLArray[indexPath.row] reply] != nil || [self.PLArray[indexPath.row] reply] != NULL) {
                return 152;
            }else{
                return 152 - 80;
            }
        }
    }
}

- (void)AAABBB{//试听点击事件
    
    CLPlayerView *playerView = [[CLPlayerView alloc] initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT - (WSCREENH_HEIGHT - WSCREENH_WIDTH*9/16))];
    
    _playerView = playerView;
    [self.view addSubview:_playerView];
    //    //重复播放，默认不播放
    //    _playerView.repeatPlay = YES;
    //    //当前控制器是否支持旋转，当前页面支持旋转的时候需要设置，告知播放器
    _playerView.isLandscape = YES;
    //    //设置等比例全屏拉伸，多余部分会被剪切
    //    _playerView.fillMode = ResizeAspectFill;
    //    //设置进度条背景颜色
    _playerView.progressBackgroundColor = [UIColor colorWithRed:0.13 green:0.13 blue:0.13 alpha:1];
    //    //设置进度条缓冲颜色
    _playerView.progressBufferColor = [UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1];
    //    //设置进度条播放完成颜色
    _playerView.progressPlayFinishColor = [UIColor colorWithRed:0.36 green:0.76 blue:0.16 alpha:1];
    //    //全屏是否隐藏状态栏
    _playerView.fullStatusBarHidden = YES;
    //    //是否静音，默认NO
    //    _playerView.mute = YES;
    //    //转子颜色
    //    _playerView.strokeColor = [UIColor redColor];
    //    //工具条消失时间，默认10s
    //    _playerView.toolBarDisappearTime = 15;
    //视频地址http://ojwzdahk1.bkt.clouddn.com/%E5%9F%8E%E5%BB%BA%E7%A8%8E%E3%80%81%E6%95%99%E8%82%B2%E8%B4%B9%E9%99%84%E5%8A%A0.flv
    //http://ojwzdahk1.bkt.clouddn.com/MP4%E5%9B%BD%E7%A8%8E%E5%85%AC%E5%91%8A2017%E5%B9%B411%E5%8F%B7.mp4

    if (self.XQArray.count > 0 && self.XQArray != nil) {

        if ([[self.XQArray[0] isfree] isEqualToString:@"N"]) {//收费
//            if ([[self.XQArray[0] payments]  isEqualToString:@"paiderror"] || [[self.XQArray[0] payments] isEqualToString:@"cphylim"] ||[[self.XQArray[0] payments] isEqualToString:@"nologin"] ||[[self.XQArray[0] payments] isEqualToString:@"nopay"]) {//没交钱
//                _playerView.url = [NSURL URLWithString:[self.XQArray[0] freeurl]];//试听URL
//            } else {//交了钱
//                _playerView.url = [NSURL URLWithString:[self.XQArray[0] videourl]];//完整URL
//            }
        //换种判断方式
            if ([[self.XQArray[0] payments] isEqualToString:@"paid"] ||[[self.XQArray[0] payments] isEqualToString:@"gjhy"]) {//免费或交了钱的
                _playerView.url = [NSURL URLWithString:[self.XQArray[0] videourl]];//完整URL
            } else {//交了钱
                _playerView.url = [NSURL URLWithString:[self.XQArray[0] freeurl]];//试听URL
            }
        }else{//免费
            _playerView.url = [NSURL URLWithString:[self.XQArray[0] videourl]];//完整URL
        }
    }
    
    //播放
    [_playerView playVideo];
    //返回按钮点击事件回调,小屏状态才会调用，全屏默认变为小屏
    [_playerView backButton:^(UIButton *button) {
        WLog(@"返回按钮被点击");
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
    //播放完成回调
    [_playerView endPlay:^{
        //销毁播放器
        [_playerView destroyPlayer];
        _playerView = nil;
        WLog(@"播放完成");
    }];
    
}

- (void)next{
    _playerView.url = [NSURL URLWithString:@"http://wvideo.spriteapp.cn/video/2016/0709/5781023a979d7_wpd.mp4"];
    [_playerView playVideo];
}

-(void)viewDidDisappear:(BOOL)animated{
    [_playerView destroyPlayer];
    _playerView = nil;
}
#pragma mark -- 需要设置全局支持旋转方向，然后重写下面三个方法可以让当前页面支持多个方向
// 是否支持自动转屏
- (BOOL)shouldAutorotate {
    return YES;
}
// 支持哪些屏幕方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}
// 默认的屏幕方向（当前ViewController必须是通过模态出来的UIViewController（模态带导航的无效）方式展现出来的，才会调用这个方法）
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

- (IBAction)LJGMBtn:(id)sender {
    WLog(@"立即购买");
    [self requestWdjf];

//    if (self.XQArray.count == 0) {
//        return;
//    }
//    if (!self.XQArray[0] || ![self.XQArray[0] payments]) {
//        return;
//    }
//    WLog(@"%@",[self.XQArray[0] payments]);
//    if (![[self.XQArray[0] selectkc] isEqualToString:@"0"] && ![WShareUtil strNilOrEmpty:[self.XQArray[0] selectkc]]) {
//
//        [self openIsSelectMemberSheet];
//
////        UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"您是金卡会员，可选20门课，目前剩余16门可选，确定继续选课吗？" message:nil
////                                                           delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
////
////        alerView.tag = 555;
////        [alerView show];
//
//    } else {
//
//        if ([SKPaymentQueue canMakePayments]) {
//            if ([WShareUtil sharedData].dicSession) {
//                BuyVIPViewController *bugVc = [[BuyVIPViewController alloc] init];
//                bugVc.title = @"订单明细";
//                bugVc.vdModel = self.XQArray[0];
//                [self.navigationController pushViewController:bugVc animated:YES];
//            } else {
//                [self openMemberSheet];
//                //            UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"温馨提示"
//                //                                                                message:@"您的还未登录，游客模式购买（仅限本设备观看），确定以游客的形式购买吗？"
//                //                                                               delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"确定",nil];
//                //            [alerView show];
//
//
//            }
//        } else {
//            UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"提示"
//                                                                message:@"您的手机没有打开程序内付费购买"
//                                                               delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
//
//            [alerView show];
//        }
//    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (alertView.tag == 556) {
        if (buttonIndex == 1) {
            [self requestSubmitChooseCourse];
        }
    }else if (alertView.tag == 557) {
        if (buttonIndex == 1) {
            AccountViewController *accountVc = [[AccountViewController alloc] init];
            [self.navigationController pushViewController:accountVc animated:YES];
        }
    } else {
        if (buttonIndex == 1) {
            BuyVIPViewController *bugVc = [[BuyVIPViewController alloc] init];
            bugVc.title = @"订单明细";
            bugVc.vdModel = self.XQArray[0];
            [self.navigationController pushViewController:bugVc animated:YES];
        }
    }
}

// 提交选课
- (void)requestSubmitChooseCourse {
    NSString *username;
    NSDictionary *parametersDict;
    NSString *nologinuser = [WShareUtil getUUID];
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"content":@{@"id":_strId,@"pid":strKxkcs,@"revert":@"chooseCourse",@"username":username},@"mode":@"native",@"service":@"train"};
    }else {
        parametersDict = @{@"content":@{@"id":_strId,@"pid":strKxkcs,@"revert":@"chooseCourse",@"nologinuser":nologinuser},@"mode":@"native",@"service":@"train"};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};

    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {

        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];
        if([returnDic[@"resultCode"] isEqualToString:@"SUCCEED"]){

            VideoDetailModel *vdModel = self.XQArray[0];
            vdModel.payments = @"paid";
            [self.XQArray removeAllObjects];
            [self.XQArray addObject:vdModel];

            [WShareUtil showAlert:ALERT_TITLE message:returnDic[@"errorInfo"]];
            [self canWatchCourse];
            NSString *strTag = [NSString stringWithFormat:@"%zd",_intTag];
            if ([WShareUtil strNilOrEmpty:_symbol]) {
                _symbol = @"";
            }
            [WShareUtil sharedData].dicSleSymbol = @{@"boughten":@"0",@"chosen":@"1",@"index":strTag,@"id":_strId,@"symbol":_symbol};
        }else {
            [WShareUtil showAlert:ALERT_TITLE message:@"选课失败"];
        }

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (IBAction)MFSTBtn:(id)sender {
    
    [self AAABBB];
    if ([WShareUtil sharedData].dicSession) {
        [self WDKCJL];//课程记录接口
    }else{
        WLog(@"未登录试听");
    }
}

- (IBAction)FHBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)backBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)faSongBtn:(id)sender {
    
    WLog(@"下发送");
    [SVProgressHUD showImage:nil status:@"请输入内容"];
    [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
    [SVProgressHUD dismissWithDelay:1.];
    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];   //背景颜色
}

-(void)btnOfSendClick {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)fsClick {
    WLog(@"上发送");
    WLog(@"%@",_textView.text);
    // 判断输入内容是否有表情，有则不能提交
    if ([_textView.text stringContainsEmoji:_textView.text]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"评论内容暂不支持表情" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        _textView.text = @"";
        return;
    }
    
    if ([_textView.text disable_emoji:_textView.text]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"评论内容暂不支持表情" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        _textView.text = @"";
        return;
    }
    
    [self requestDataSubmitComment];
    [[IQKeyboardManager sharedManager] doneAction:nil];
}

#pragma mark - UITextViewDelegate

-(void)textViewDidBeginEditing:(UITextView *)textView {
    WLog(@"点");
//    _myTableView.scrollEnabled = NO;
//
//    textView.returnKeyType = UIReturnKeyDone;//完成按钮
//    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT-60)];
//    bgView.backgroundColor = [UIColor grayColor];
//    bgView.alpha = 0.4;
//    bgView.tag = 20000;
//    [self.view addSubview:bgView];
//    _inputView.backgroundColor = [UIColor whiteColor];
//
//    [self.view addSubview:_inputView];

}
- (void)textViewDidChange:(UITextView *)textView {
    NSUInteger length = [textView.text length];
    NSRange range = NSMakeRange(length - 1, 1);
    if([[textView.text substringWithRange:range] isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    // 该判断用于联想输入, 限制输入字数500
    if (textView.text.length > 499 ) {
        _textView.text = [textView.text substringToIndex:500];
    }
    
    if ([textView.text length] == 0) {
        [self.lbOfPlaceholder setHidden:NO];
        [fsBtn setUserInteractionEnabled:NO];
        [fsBtn setBackgroundColor:[UIColor grayColor]];
        
    }else {
        [self.lbOfPlaceholder setHidden:YES];
        [fsBtn setUserInteractionEnabled:YES];
        [fsBtn setBackgroundColor:[UIColor colorWithRed:0.09 green:0.69 blue:0.11 alpha:1]];
    }

    if (_textViewQ.text.length == 0) {
        _qsrnrLb.hidden = NO;
    }
    else {
        _qsrnrLb.hidden = YES;
    }
}

-(void)wkeyboardWillShow:(NSNotification *)notification
{
    //这样就拿到了键盘的位置大小信息frame，然后根据frame进行高度处理之类的信息
    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat endHeight = WSCREENH_HEIGHT - self.inputView.bounds.size.height - frame.size.height;
    
    _inputView.frame = CGRectMake(0, endHeight, WSCREENH_WIDTH, 60);
//    _textView.text = _textViewQ.text;
    if ([_textView.text length] == 0) {
        [self.lbOfPlaceholder setHidden:NO];
        [fsBtn setUserInteractionEnabled:NO];
        [fsBtn setBackgroundColor:[UIColor grayColor]];
        
    }else {
        [self.lbOfPlaceholder setHidden:YES];
        [fsBtn setUserInteractionEnabled:YES];
        [fsBtn setBackgroundColor:[UIColor colorWithRed:0.09 green:0.69 blue:0.11 alpha:1]];
    }
    if (_textViewQ.text.length == 0) {
        _qsrnrLb.hidden = NO;
    }
    else {
        _qsrnrLb.hidden = YES;
    }
}
/**
 *  键盘将要隐藏
 *
 *  @param notification 通知
 */
-(void)wkeyboardWillHidden:(NSNotification *)notification
{
    _inputView.frame = CGRectMake(0, WSCREENH_HEIGHT, WSCREENH_WIDTH, 150);
    UIView *bgView = [self.view viewWithTag:20000];
    [bgView removeFromSuperview];
    [self.btnSend setBackgroundImage:[UIImage imageNamed:@"fabiao2"] forState:UIControlStateNormal];
    [self.btnSend setUserInteractionEnabled:NO];
//    _textViewQ.text = _textView.text;
//    if (_textViewQ.text.length == 0) {
//        _qsrnrLb.hidden = NO;
//    }
//    else {
//        _qsrnrLb.hidden = YES;
//    }
}

- (IBAction)textBtn:(id)sender {
//    if ([WShareUtil sharedData].dicSession) {
        UIView *bgView = [[UIView alloc]initWithFrame:self.view.bounds];
        bgView.backgroundColor = [UIColor grayColor];
        bgView.alpha = 0.4;
        bgView.tag = 20000;
        [self.view addSubview:bgView];
        
        _inputView.backgroundColor = [UIColor whiteColor];
        
        [self.view addSubview:_inputView];
        
        _textView = [[UITextView alloc]initWithFrame:CGRectMake(39, 13, WSCREENH_WIDTH - 79 - 40, 35)];
        _textView.layer.masksToBounds = YES;
        _textView.layer.cornerRadius = 20;
        _textView.delegate = self;
        _textView.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1];
        _textView.textContainerInset = UIEdgeInsetsMake(6, 5, 0, 0);
        _textView.font = [UIFont systemFontOfSize:15];
        [_inputView addSubview:_textView];
        
        [_textView becomeFirstResponder];
        
        //    _textView.inputAccessoryView = nil;
        self.lbOfPlaceholder = [[UILabel alloc]initWithFrame:CGRectMake(48, 20, 90, 21)];
        self.lbOfPlaceholder.enabled = NO;
        self.lbOfPlaceholder.text = @"请输入内容";
        self.lbOfPlaceholder.font = [UIFont systemFontOfSize:15];
        self.lbOfPlaceholder.textColor = [UIColor colorWithRed:0.65 green:0.65 blue:0.65 alpha:1];
        [_inputView addSubview:self.lbOfPlaceholder];
        
        // 限制500字内容
        //    self.lbWBZContent = [[UILabel alloc]initWithFrame:CGRectMake(20, 95, 200, 21)];
        //    self.lbWBZContent.enabled = NO;
        //    self.lbWBZContent.text = @"限制500字内容";
        //    self.lbWBZContent.font = [UIFont systemFontOfSize:12];
        //    self.lbWBZContent.textColor = [UIColor greenColor];
        //    [_inputView addSubview:self.lbWBZContent];
        
        UIImageView *imView = [[UIImageView alloc]initWithFrame:CGRectMake(13, 17, 13, 26)];
        imView.image = [UIImage imageNamed:@"KCMX_9"];
        [_inputView addSubview:imView];
        
        _btnSend = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 60)];
        //    [_btnSend setUserInteractionEnabled:NO];
        [_btnSend setBackgroundColor:[UIColor clearColor]];
        [_btnSend addTarget:self action:@selector(btnOfSendClick) forControlEvents:UIControlEventTouchUpInside];
        
        [_inputView addSubview:_btnSend];
        
        //发送按钮
        fsBtn = [[UIButton alloc]initWithFrame:CGRectMake(WSCREENH_WIDTH - 10 - 59, 11, 59, 39)];
        [fsBtn setTitle:@"发送" forState:UIControlStateNormal];
        [fsBtn setUserInteractionEnabled:NO];
        [fsBtn setTintColor:[UIColor whiteColor]];
        [fsBtn setBackgroundColor:[UIColor grayColor]];
        [fsBtn addTarget:self action:@selector(fsClick) forControlEvents:UIControlEventTouchUpInside];
        
        [_inputView addSubview:fsBtn];
//    } else {
//        [SVProgressHUD showImage:nil status:@"请先登录"];
//        [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
//        [SVProgressHUD dismissWithDelay:1.];
//        [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];   //背景颜色
//    }

}

#pragma mark - 提交评论
-(void)requestDataSubmitComment {
    /*
     mode:native,service:comment,content:{revert:submit,username:？,dto:{from:xt,id:?,content=?}}
     */
    NSString *username;
    NSDictionary *parametersDict;
    NSString *nologinuser = [WShareUtil getUUID];
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"revert":@"submit",@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"dto":@{@"from":@"xt",@"id":_strId,@"content":_textView.text}}};
    }else {
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"revert":@"submit",@"nologinuser":nologinuser,@"dto":@{@"from":@"xt",@"id":_strId,@"content":_textView.text}}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};
    
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];
        
        if([returnDic[@"resultCode"] isEqualToString:@"SUCCEED"]){

//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"评论提交成功！" delegate:nil cancelButtonTitle:SURE otherButtonTitles:nil];
//            [alert show];
//            return;
            [self requestPingLunListDataisRefresh:YES];//下载详情评论列表

        }else if([returnDic[@"resultCode"] isEqualToString:@"DTO_ERROR"]){

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"提交数据格式错误！" delegate:nil cancelButtonTitle:SURE otherButtonTitles:nil];
            [alert show];
            return;
        }
        
    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (IBAction)DengLuBtn:(id)sender {
    
    if ([WShareUtil sharedData].dicSession) {
        
        [SVProgressHUD showImage:nil status:@"您已登录"];
        [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
        [SVProgressHUD dismissWithDelay:1.];
        [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];   //背景颜色
        
    } else {
        LoginViewController *loginVc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVc animated:YES];
    }
}
//@"http://www.sx95113.com/wapfww/kcdetail?type=hxjt&KC_ID=2420&source=zst"
- (IBAction)FenXiangBtn:(id)sender {
    
    //NSString *shareUrl = [NSString stringWithFormat:@"http://mobile.csfw360.com/sharpContentApp/renderSharpContentPage?id=%@&modelName=%@&isVedio=%@&uid=%@",_dicReturn[@"id"],@"article",@"true",[WShareUtil sharedData].dicSession[@"userid"]];
    
    //判断SHARE_URL 是否含有?
    if ([SHARE_URL rangeOfString:@"?"].location != NSNotFound) {//前缀有问号
        _shareUrl = [NSString stringWithFormat:@"%@%@&source=zst",SHARE_URL,_strId];

    }else{//前缀无问号
        _shareUrl = [NSString stringWithFormat:@"%@%@?source=zst",SHARE_URL,_strId];

    }
    WLog(@"%@",_shareUrl);
    
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone)]];
    // --- 设置分享面板的UI
    [UMSocialShareUIConfig shareInstance].shareTitleViewConfig.isShow = YES;//有无标题
    [UMSocialShareUIConfig shareInstance].shareCancelControlConfig.isShow = YES;//有无取消
    [UMSocialShareUIConfig shareInstance].shareTitleViewConfig.shareTitleViewTitleString = @"";//标题文字
    [UMSocialShareUIConfig shareInstance].shareCancelControlConfig.shareCancelControlText = @"取消";//取消文字
    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageMaxItemWidth = 50;//每页Items的最大宽度(白圈的大小)
    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageMaxItemHeight = 90;//每页Items的最大高度(背景的高低)
    
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的1确定所选平台进行下一步操作
        
        /*
         详情
         */
        NSString *descrStr = [WShareUtil filterHTML:[self.XQArray[0] brief]];
        descrStr = [descrStr stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];//去掉特殊符号
        descrStr = [descrStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//去掉左右两端的空格
        /*
         图片
         */
        NSURL *imgUrl = [NSURL URLWithString:[self.XQArray[0] imgsrc]];
        NSData *dateImg = [NSData dataWithContentsOfURL:imgUrl];
        
        if (dateImg == nil || dateImg.length <= 0) {
            UMShareWebpageObject *webO = [UMShareWebpageObject shareObjectWithTitle:[self.XQArray[0] StrTitlestr] descr:descrStr thumImage:[UIImage imageNamed:@"logo_share.png"]];
            webO.webpageUrl = [NSString stringWithFormat:@"%@&source=zst",_shareUrl];
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:[UMSocialMessageObject messageObjectWithMediaObject:webO] currentViewController:self completion:^(id result, NSError *error) {
                
                NSString *message = nil;
                if (!error) {
                    message = [NSString stringWithFormat:@"分享成功"];
                } else {
                    message = [NSString stringWithFormat:@"失败原因Code: %d\n",(int)error.code];
                    
                }
            }];
        } else {
            UMShareWebpageObject *webO = [UMShareWebpageObject shareObjectWithTitle:[self.XQArray[0] StrTitlestr] descr:descrStr thumImage:dateImg];
            webO.webpageUrl = [NSString stringWithFormat:@"%@&source=zst",_shareUrl];
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:[UMSocialMessageObject messageObjectWithMediaObject:webO] currentViewController:self completion:^(id result, NSError *error) {
                
                NSString *message = nil;
                if (!error) {
                    message = [NSString stringWithFormat:@"分享成功"];
                } else {
                    message = [NSString stringWithFormat:@"失败原因Code: %d\n",(int)error.code];
                    
                }
            }];
        }
    }];
}

#pragma mark - 我的课程记录
-(void)WDKCJL {

    /*
     mode:native,service:train,content:{revert:record,id:?,username:?}
     */
    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"revert":@"record",@"id":_strId,@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"]}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};
    
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if([returnDic[@"resultCode"] isEqualToString:@"SUCCEED"]){
            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"更新记录成功" delegate:nil cancelButtonTitle:SURE otherButtonTitles:nil];
//            [alert show];
//            return;
            
        }else if([returnDic[@"resultCode"] isEqualToString:@"DTO_ERROR"]){
            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"提交数据格式错误！" delegate:nil cancelButtonTitle:SURE otherButtonTitles:nil];
//            [alert show];
//            return;
            
        }
        
    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (void)openMemberSheet {

    bgMebemView = [[UIView alloc] initWithFrame:self.view.bounds];
    bgMebemView.backgroundColor = WRGBAColor(0, 0, 0, 0.5);
    [self.view addSubview:bgMebemView];
    [bgMebemView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];

//    viewContent = [[UIView alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 280) * 0.5, (WSCREENH_HEIGHT - 240) * 0.5, 280, 240)];
    viewContent = [[UIView alloc] init];
    [self.view addSubview:viewContent];

    viewContent.backgroundColor = WRGBColor(255, 255, 255);
    viewContent.layer.cornerRadius = 10;
    [viewContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(280, 240));
    }];

    UILabel *lbTit = [[UILabel alloc] initWithFrame:CGRectMake(0, 15, 280, 20)];
    lbTit.backgroundColor = [UIColor whiteColor];
    lbTit.text = @"购买课程";
    lbTit.font = [UIFont systemFontOfSize:16];
    lbTit.textAlignment = NSTextAlignmentCenter;
    [viewContent addSubview:lbTit];

    UILabel *lbSubheading1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 45, 280, 20)];
    lbSubheading1.backgroundColor = [UIColor whiteColor];
    lbSubheading1.font = [UIFont systemFontOfSize:15];
    lbSubheading1.text = @"登录掌税通购买:可跨平台观看课程";
    lbSubheading1.textAlignment = NSTextAlignmentCenter;
    [viewContent addSubview:lbSubheading1];

    UILabel *lbSubheading2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, 280, 20)];
    lbSubheading2.backgroundColor = [UIColor whiteColor];
    lbSubheading2.font = [UIFont systemFontOfSize:15];
    lbSubheading2.text = @"游客身份购买:仅限本设备看课程";
    lbSubheading2.textAlignment = NSTextAlignmentCenter;
    [viewContent addSubview:lbSubheading2];

    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 99, 280, 1)];
    lineView.backgroundColor = WRGBColor(243, 243, 243);
    [viewContent addSubview:lineView];

    UIButton *btnMember = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 280, 44)];
    [btnMember.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [btnMember setTitle:@"登录掌税通购买" forState:UIControlStateNormal];
    [btnMember setTitleColor:WRGBColor(46, 141, 238) forState:UIControlStateNormal];
    btnMember.tag = 100;
    [btnMember addTarget:self action:@selector(btnOpenClick:) forControlEvents:UIControlEventTouchUpInside];
    [viewContent addSubview:btnMember];

    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 143, 280, 1)];
    lineView1.backgroundColor = WRGBColor(243, 243, 243);
    [viewContent addSubview:lineView1];

    UIButton *btnTourist = [[UIButton alloc] initWithFrame:CGRectMake(0, 144, 280, 44)];
    [btnTourist.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [btnTourist setTitle:@"游客身份购买" forState:UIControlStateNormal];
    [btnTourist setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btnTourist.tag = 110;
    [btnTourist addTarget:self action:@selector(btnOpenClick:) forControlEvents:UIControlEventTouchUpInside];
    [viewContent addSubview:btnTourist];

    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 187, 280, 1)];
    lineView2.backgroundColor = WRGBColor(243, 243, 243);
    [viewContent addSubview:lineView2];

    UIButton *btnLogin = [[UIButton alloc] initWithFrame:CGRectMake(0, 188, 280, 44)];
    [btnLogin.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [btnLogin setTitle:@"取消" forState:UIControlStateNormal];
    [btnLogin addTarget:self action:@selector(btnOpenClick:) forControlEvents:UIControlEventTouchUpInside];
    btnLogin.tag = 120;
    [btnLogin setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [viewContent addSubview:btnLogin];
}

- (void)btnOpenClick:(UIButton *)btn {
    if (btn.tag == 100) {

        [WShareUtil sharedData].Who = @"KCGM";
        LoginViewController *loginVc = [[LoginViewController alloc]init];
        [self.navigationController pushViewController:loginVc animated:YES];
    } else if (btn.tag == 110) {
        BuyVIPViewController *bugVc = [[BuyVIPViewController alloc] init];
        bugVc.title = @"订单明细";
        if (self.XQArray == nil || self.XQArray.count <= 0) {
            return;
        }
        bugVc.vdModel = self.XQArray[0];
        [self.navigationController pushViewController:bugVc animated:YES];
    } else {

    }
    [bgMebemView removeFromSuperview];
    [viewContent removeFromSuperview];
}

- (void)dealloc {
    //移除所有通知监控
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)openIsSelectMemberSheet {

        bgSleMemberV = [[UIView alloc] initWithFrame:self.view.bounds];
        bgSleMemberV.backgroundColor = WRGBAColor(0, 0, 0, 0.5);
        [self.view addSubview:bgSleMemberV];
        [bgSleMemberV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];

        memberVcontent = [[UIView alloc] init];
        [self.view addSubview:memberVcontent];
        memberVcontent.backgroundColor = WRGBColor(255, 255, 255);
        memberVcontent.layer.cornerRadius = 10;
        [memberVcontent mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.centerY.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(280, 200));
        }];

    UILabel *lbSubheading2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 15, 280, 30)];
    lbSubheading2.backgroundColor = [UIColor whiteColor];
    lbSubheading2.font = [UIFont systemFontOfSize:18];
    lbSubheading2.text = @"请您选择观看方式";
    lbSubheading2.textAlignment = NSTextAlignmentCenter;
    [memberVcontent addSubview:lbSubheading2];

    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 61, 280, 1)];
    lineView.backgroundColor = WRGBColor(243, 243, 243);
    [memberVcontent addSubview:lineView];

    UIButton *btnMember = [[UIButton alloc] initWithFrame:CGRectMake(0, 62, 280, 44)];
    [btnMember.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [btnMember setTitle:@"添加到您的选课列表" forState:UIControlStateNormal];
    [btnMember setTitleColor:WRGBColor(46, 141, 238) forState:UIControlStateNormal];
    btnMember.tag = 210;
    [btnMember addTarget:self action:@selector(btnSlecetClick:) forControlEvents:UIControlEventTouchUpInside];
    [memberVcontent addSubview:btnMember];

    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 107, 280, 1)];
    lineView1.backgroundColor = WRGBColor(243, 243, 243);
    [memberVcontent addSubview:lineView1];

    UIButton *btnTourist = [[UIButton alloc] initWithFrame:CGRectMake(0, 108, 280, 44)];
    [btnTourist.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [btnTourist setTitle:@"付费购买" forState:UIControlStateNormal];
    [btnTourist setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btnTourist.tag = 220;
    [btnTourist addTarget:self action:@selector(btnSlecetClick:) forControlEvents:UIControlEventTouchUpInside];
    [memberVcontent addSubview:btnTourist];

    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 153, 280, 1)];
    lineView2.backgroundColor = WRGBColor(243, 243, 243);
    [memberVcontent addSubview:lineView2];

    UIButton *btnLogin = [[UIButton alloc] initWithFrame:CGRectMake(0, 154, 280, 44)];
    [btnLogin.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [btnLogin setTitle:@"取消" forState:UIControlStateNormal];
    [btnLogin addTarget:self action:@selector(btnSlecetClick:) forControlEvents:UIControlEventTouchUpInside];
    btnLogin.tag = 230;
    [btnLogin setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [memberVcontent addSubview:btnLogin];

}

- (void)btnSlecetClick:(UIButton *)btn {
    if (btn.tag == 210) {

        NSString *strTit = [NSString stringWithFormat:@"您还可选%@门课，确定继续选课吗？",jFDic[@"kxkcs"]];
        UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:strTit
                                                           delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        alerView.tag = 556;
        [alerView show];

    } else if (btn.tag == 220) {

        if (self.XQArray.count <= 0) {
            return;
        }

        if ([[WShareUtil sharedData].strRemaining integerValue] >= [[self.XQArray[0] charged] integerValue]) {
            if ([WShareUtil sharedData].dicSession) {
                BuyVIPViewController *bugVc = [[BuyVIPViewController alloc] init];
                bugVc.title = @"订单明细";
                bugVc.vdModel = self.XQArray[0];
                [self.navigationController pushViewController:bugVc animated:YES];
            } else {

                [self openMemberSheet];
                //            UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"温馨提示"
                //                                                                message:@"您的还未登录，游客模式购买（仅限本设备观看），确定以游客的形式购买吗？"
                //                                                               delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"确定",nil];
                //            [alerView show];

            }
        } else {
            UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                                message:@"您的账号余额不足，是否进入充值界面"
                                                               delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

            alerView.tag = 557;

            [alerView show];
        }
    } else {

    }
    [bgSleMemberV removeFromSuperview];
    [memberVcontent removeFromSuperview];
}

- (void)requestWdjf{

    NSDictionary *parametersDict;
    NSString *nologinuser;
    if ([WShareUtil sharedData].dicSession) {
        parametersDict = @{@"content":@{@"revert":@"basic",@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"]},@"mode":@"native",@"service":@"mine"};
    } else {
        nologinuser = [WShareUtil getUUID];
        parametersDict = @{@"content":@{@"revert":@"basic",@"nologinuser":nologinuser},@"mode":@"native",@"service":@"mine"};
    }
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"false"]) {
            [WShareUtil sharedData].strRemaining = @"0.0";
            [WShareUtil sharedData].strlxmc = @"";
            return;
        }

        [WShareUtil sharedData].strRemaining = returnDic[@"remaining"];
        [WShareUtil sharedData].strlxmc = returnDic[@"lxmc"];

        jFDic = returnDic;
        if ([returnDic[@"kxkcs"] intValue] > 0) {

            [self openIsSelectMemberSheet];
            strKxkcs = returnDic[@"kxkcs"];
        } else {

            if (self.XQArray.count <= 0) {
                return;
            }

            if ([returnDic[@"remaining"] integerValue] >= [[self.XQArray[0] charged] integerValue]) {

                if ([WShareUtil sharedData].dicSession) {
                    BuyVIPViewController *bugVc = [[BuyVIPViewController alloc] init];
                    bugVc.title = @"订单明细";
                    bugVc.vdModel = self.XQArray[0];
                    [self.navigationController pushViewController:bugVc animated:YES];
                } else {
                    [self openMemberSheet];
                }
            } else {
                UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                                    message:@"您的账号余额不足，是否进入充值界面"
                                                                   delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

                alerView.tag = 557;

                [alerView show];
            }
        }

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

@end

